﻿using Castle.Core;
using Castle.MicroKernel;
using System.Linq;
using System.Reflection;
using Yto.Common.Dependency;

namespace Yto.Unitwork
{
    public static class UnitworkRegistrar
    {
        public static void Initialize(ICtnManager ctnManager)
        {
            ctnManager.Container.Kernel.ComponentRegistered += Kernel_ComponentRegistered;
        }

        private static void Kernel_ComponentRegistered(string key, IHandler handler)
        {
            if (UnitworkHelper.IsUnitworkClass(handler.ComponentModel.Implementation))
            {
                handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitworkInterceptor)));
            }else if(handler.ComponentModel.Implementation.GetMethods(BindingFlags.Public
                | BindingFlags.Instance | BindingFlags.NonPublic)
                .Any(UnitworkHelper.IsDefindUnitwork))
            {
                handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitworkInterceptor)));
            }
        }
    }
}
